package com.oms.web.interceptor;

import java.net.URLDecoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.oms.domain.User;
import com.oms.service.UserService;
import com.oms.util.POtoVOUtil;
import com.oms.web.form.UserForm;

public class AutoLoginInterceptor implements HandlerInterceptor {
	
	@Autowired
	UserService userServiceInter;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if(request.getSession(false)==null || request.getSession().getAttribute("user")==null){
			Cookie [] cs =request.getCookies();
			Cookie findC=null;
			if(cs!=null){
				for(Cookie c: cs){
					if("autoLogin".equals(c.getName())){
						findC = c;
						break;
					}
				}
			}
			if(findC!=null){
				System.out.println("找到该cookie");
				String v = URLDecoder.decode(findC.getValue(), "utf-8");
				String userEmail = v.split(":")[0];
				String password = v.split(":")[1];
				User user=userServiceInter.loginByEmail(userEmail, password);
				if(user!=null){
					System.out.println("实现自动登录");
					request.getSession().setAttribute("user", POtoVOUtil.copyObject(user, UserForm.class));
				}
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}	

}
